package com.gateio.flutter.lib_furnace

import android.app.Activity
import android.content.Context
import android.content.Intent
import com.gateio.flutter.lib_furnace.container.FragmentConfigureFlutterEngine
import com.gateio.flutter.lib_furnace.container.GTFlutterDialogActivity
import com.gateio.flutter.lib_furnace.container.GTFlutterFragment
import com.gateio.flutter.lib_furnace.container.GTFlutterFragmentActivity
import com.gateio.flutter.lib_furnace.container.GTFlutterViewFragment
import io.flutter.embedding.android.FlutterActivityLaunchConfigs
import io.flutter.embedding.android.RenderMode
import io.flutter.embedding.android.TransparencyMode

/**
 * Author: Shper
 * Created: 2024/1/26
 */
class GTFlutterBuilder(private var routerName: String) {

    // Activity、Fragment 通用
    private var initExtendParams: MutableMap<String, Any> = mutableMapOf()
    private var routeParams: Map<String, Any> = emptyMap()
    private var customEngineId: String = ""
    private var isDialog: Boolean = false
    private var transparentStatusBar: Boolean = true
    private var animationType: AnimationType = AnimationType.rightInRightOut
    private var dialogEnableLandscape: Boolean = false
    private var configureFlutterEngineFun: FragmentConfigureFlutterEngine? = null
    // 背景是否透明
    private var transparencyMode: TransparencyMode? = null
    // 渲染模式
    private var renderMode: RenderMode? = null
    // 是否自定义设置 主题模式
    private var customDarkMode: Boolean? = null
    // 页面销毁时，是否销毁引擎
    private var destroyEngineWithHost = true

    // Activity 专用
    private var flags: Int? = null
    private var isSinglePage = false

    // Fragment 专用
    private var handleDeeplinking = false
    private var shouldAttachEngineToActivity = true
    private var shouldAutomaticallyHandleOnBackPressed = false
    private var shouldDelayFirstAndroidViewDraw = false

    fun routeParams(routeParams: Map<String, Any>): GTFlutterBuilder {
        this.routeParams = routeParams
        return this
    }

    fun renderMode(renderMode: RenderMode): GTFlutterBuilder {
        this.renderMode = renderMode
        return this
    }

    fun customEngineId(customEngineId: String): GTFlutterBuilder {
        this.customEngineId = customEngineId
        return this
    }

    fun isDialog(isDialog: Boolean): GTFlutterBuilder {
        this.isDialog = isDialog
        return this
    }

    fun transparentStatusBar(transparentStatusBar: Boolean): GTFlutterBuilder {
        this.transparentStatusBar = transparentStatusBar
        return this
    }

    fun animationType(animationType: AnimationType): GTFlutterBuilder {
        this.animationType = animationType
        return this
    }

    fun customDarkMode(isDarkMode: Boolean): GTFlutterBuilder {
        this.customDarkMode = isDarkMode
        return this
    }

    fun dialogEnableLandscape(dialogEnableLandscape: Boolean): GTFlutterBuilder {
        this.dialogEnableLandscape = dialogEnableLandscape
        return this
    }

    fun onConfigureFlutterEngine(configureFlutterEngineFun: FragmentConfigureFlutterEngine?): GTFlutterBuilder {
        this.configureFlutterEngineFun = configureFlutterEngineFun
        return this
    }

    // 初始化 扩展参数
    fun addInitExtendParams(map: Map<String, Any>): GTFlutterBuilder {
        this.initExtendParams.putAll(map)
        return this
    }

    // 初始化 扩展参数
    fun addInitExtendParam(key: String, value: Any): GTFlutterBuilder {
        this.initExtendParams[key] = value
        return this
    }

    // 是否单独页面
    fun singlePage() : GTFlutterBuilder {
        isSinglePage = true
        return this
    }

    // 添加 Flags
    fun addFlags(flags: Int): GTFlutterBuilder {
        this.flags = if (this.flags == null) {
            flags
        } else {
            this.flags?.or(flags) ?: flags
        }
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.transparencyMode
     * @see io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode
     */
    fun backgroundMode(transparencyMode: TransparencyMode): GTFlutterBuilder {
        this.transparencyMode = transparencyMode
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.transparencyMode
     * @see io.flutter.embedding.android.FlutterActivityLaunchConfigs.BackgroundMode
     */
    fun transparencyMode(transparencyMode: TransparencyMode): GTFlutterBuilder {
        this.transparencyMode = transparencyMode
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.destroyEngineWithFragment
     */
    fun destroyEngineWithHost(destroyEngineWithHost: Boolean): GTFlutterBuilder {
        this.destroyEngineWithHost = destroyEngineWithHost
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.handleDeeplinking
     */
    fun handleDeeplinking(handleDeeplinking: Boolean): GTFlutterBuilder {
        this.handleDeeplinking = handleDeeplinking
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.shouldAttachEngineToActivity
     */
    fun shouldAttachEngineToActivity(shouldAttachEngineToActivity: Boolean): GTFlutterBuilder {
        this.shouldAttachEngineToActivity = shouldAttachEngineToActivity
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.shouldAutomaticallyHandleOnBackPressed
     */
    fun shouldAutomaticallyHandleOnBackPressed(shouldAutomaticallyHandleOnBackPressed: Boolean): GTFlutterBuilder {
        this.shouldAutomaticallyHandleOnBackPressed = shouldAutomaticallyHandleOnBackPressed
        return this
    }

    /**
     * @see io.flutter.embedding.android.FlutterFragment.CachedEngineFragmentBuilder.shouldDelayFirstAndroidViewDraw
     */
    fun shouldDelayFirstAndroidViewDraw(shouldDelayFirstAndroidViewDraw: Boolean): GTFlutterBuilder {
        this.shouldDelayFirstAndroidViewDraw = shouldDelayFirstAndroidViewDraw
        return this
    }

    /**
     * 打开 Flutter 页面
     */
    fun openPage(context: Context) {
        if (isSinglePage && GTFlutter.pageStartedList.contains(routerName)) {
            return
        }

        val intent = createIntent(context)
        // 非 Activity context 时，添加 FLAG_ACTIVITY_NEW_TASK
        if (context !is Activity) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        flags?.let {
            intent.addFlags(it)
        }

        GTFlutter.pageStartedList.add(routerName)
        context.startActivity(intent)
    }

    /**
     * 打开 Flutter 页面并返回结果
     */
    fun openPageForResult(activity: Activity, requestCode: Int) {
        val intent = createIntent(activity)
        activity.startActivityForResult(intent, requestCode)
    }

    /**
     * 创建 Activity Intent
     */
    fun createIntent(context: Context): Intent {
        // 创建和复用引擎
        val engineId = GTFlutter.createAndRunEngine(
            context,
            routerName,
            routeParams,
            customEngineId,
            transparentStatusBar,
            initExtendParams,
            customDarkMode
        )
        if (isDialog) {
            // Dialog 默认 backgroundMode 为透明色
            val backgroundMode = if (transparencyMode == TransparencyMode.opaque) {
                FlutterActivityLaunchConfigs.BackgroundMode.opaque
            } else {
                FlutterActivityLaunchConfigs.BackgroundMode.transparent
            }
            // 打开 Flutter Dialog Activity 页面
            return GTFlutterDialogActivity.withCachedEngineId(engineId)
                .routerName(routerName)
                .routeParams(routeParams)
                .customEngineId(customEngineId)
                .transparentStatusBar(transparentStatusBar)
                .animationType(animationType)
                .dialogEnableLandscape(dialogEnableLandscape)
                .destroyEngineWithActivity(destroyEngineWithHost)
                .backgroundMode(backgroundMode)
                .build(context)
        } else {
            // 非 Dialog 默认 backgroundMode 为不透明色
            val backgroundMode = if (transparencyMode == TransparencyMode.transparent) {
                FlutterActivityLaunchConfigs.BackgroundMode.transparent
            } else {
                FlutterActivityLaunchConfigs.BackgroundMode.opaque
            }
            // 打开 Flutter 页面
            return GTFlutterFragmentActivity.withCachedEngineId(engineId)
                .routerName(routerName)
                .routeParams(routeParams)
                .customEngineId(customEngineId)
                .transparentStatusBar(transparentStatusBar)
                .animationType(animationType)
                .dialogEnableLandscape(dialogEnableLandscape)
                .destroyEngineWithActivity(destroyEngineWithHost)
                .backgroundMode(backgroundMode)
                .build(context)
        }
    }

    fun createFragment(context: Context): GTFlutterFragment {
        // 创建和复用引擎
        val engineId = GTFlutter.createAndRunEngine(
            context,
            routerName,
            routeParams,
            customEngineId,
            transparentStatusBar,
            initExtendParams,
            customDarkMode
        )
        // 生成 FlutterFragment
        return GTFlutterFragment.withCachedEngineId(engineId)
            .routerName(routerName)
            .routeParams(routeParams)
            .customEngineId(customEngineId)
            .transparentStatusBar(transparentStatusBar)
            .onConfigureFlutterEngine(configureFlutterEngineFun)
            .destroyEngineWithFragment(destroyEngineWithHost)
            .handleDeeplinking(handleDeeplinking)
            .renderMode(renderMode ?: RenderMode.surface)
            .transparencyMode(transparencyMode ?: TransparencyMode.transparent)
            .shouldAttachEngineToActivity(shouldAttachEngineToActivity)
            .shouldAutomaticallyHandleOnBackPressed(shouldAutomaticallyHandleOnBackPressed)
            .shouldDelayFirstAndroidViewDraw(shouldDelayFirstAndroidViewDraw)
            .build<GTFlutterFragment>()
    }

    @Deprecated("FlutterViewFragment 待废弃，请使用createFragment")
    fun createFlutterViewFragment(context: Context): GTFlutterViewFragment {
        // 创建和复用引擎
        val engineId = GTFlutter.createAndRunEngine(
            context,
            routerName,
            routeParams,
            customEngineId,
            transparentStatusBar,
            initExtendParams,
            customDarkMode
        )
        // 生成 FlutterFragment
        val flutterViewFragment = GTFlutterViewFragment.withCachedEngineId(
            routerName,
            engineId,
            renderMode ?: RenderMode.texture,
            transparencyMode ?: TransparencyMode.transparent,
            shouldAutomaticallyHandleOnBackPressed
        )
        flutterViewFragment.configureFlutterEngineFun = configureFlutterEngineFun
        return flutterViewFragment
    }

}